<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\IconRender;
use App\Admin\Repositories\WxPage;
use App\Models\WxIcon;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\Settings;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Tooltip;

class WxPageController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxPage(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('setting_url', '前端路径')->display(function () {
                if($this->type == 0 || $this->type == 1){
                    return '/pagesB/tabs/tabs?id=' . $this->id;
                }else if($this->type == 2){
                    return '/pagesB/menus/menus?id=' . $this->id;
                }else if($this->type == 3){
                    return '/pagesB/qrcode/qrcode?id=' . $this->id;
                }
                return '';
            });
            $grid->column('title');
            $grid->column('right');
            $grid->column('type')->using(FieldUtils::getPageTypes());
//            $grid->column('config');
            $grid->column('status')->using([0=>'正常',1=>'下架'])->label([0 => 'success',
                1 => 'red']);
//            $grid->column('created_at');
            // 添加不存在的字段



            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxPage(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('right');
            $show->field('type');
            $show->field('config');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxPage(), function (Form $form) {
            $modle = $form->model();

            $form->display('id');
            $res8 = __system__paycode__tip__(8);
            Tooltip::make('.mini_global_admin_open_not_support_tip')
                ->bottom()
                ->title($res8['tip']);
            $form->text('title')->help($res8['text'])->required();
            $form->multipleSelectTable('right')
                ->title('图标库')
                ->max(2)
                ->from(IconRender::make())
                ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:right')
                ->help('【暂时统一不显示】添加一个右侧，小程序不显示， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>')
                ->saveAsJson();

            $form->select('type')->options(FieldUtils::getPageTypes())->required()->when(0, function (Form $form) use ($modle) {
                $form->html(function () {
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;max-width: 200px;"><img src="https://img.mini.minisns.cn/images/page/page-tab-1.jpg" style=" width: 100%; "></div>';
                }, '');
                if($form->isCreating()){
                    $form->table('config0', FieldUtils::getPageTypes()[0], function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->multipleSelectTable('tab', 'tab内容')
                            ->title('图标库')
                            ->max(100)
                            ->from(IconRender::make())
                            ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config0:tab')
                            ->help('一个tab页面， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>');
                    })->saveAsJson();
                }else{
                    $config0 = '';
                    if($modle->type == 0){
                        $config0 = $modle->config;
                    }
                    $form->table('config0', FieldUtils::getPageTypes()[0], function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->multipleSelectTable('tab', 'tab内容')
                            ->title('图标库')
                            ->max(100)
                            ->from(IconRender::make())
                            ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config0:tab')
                            ->help('一个tab页面， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>');
                    })->saveAsJson()->value($config0);
                }

            })->when(1, function (Form $form) use ($modle) {
                $form->html(function () {
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;max-width: 200px;"><img src="https://img.mini.minisns.cn/images/page/page-tab-2.jpg" style=" width: 100%; "></div>';
                }, '');
                if($form->isCreating()){
                    $form->table('config1', FieldUtils::getPageTypes()[1], function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->multipleSelectTable('tab', 'tab内容')
                            ->title('图标库')
                            ->max(100)
                            ->from(IconRender::make())
                            ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config1:tab')
                            ->help('一个tab页面， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>');
                    })->saveAsJson();
                }else if($form->isEditing()){
                    $config1 = '';
                    if($modle->type == 1){
                        $config1 = $modle->config;
                    }
                    $form->table('config1', FieldUtils::getPageTypes()[1], function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->multipleSelectTable('tab', 'tab内容')
                            ->title('图标库')
                            ->max(100)
                            ->from(IconRender::make())
                            ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config1:tab')
                            ->help('一个tab页面， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>');
                    })->saveAsJson()->value($config1);
                }

            })->when(2, function (Form $form) use ($modle) {
                $form->html(function () {
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;max-width: 200px;"><img src="https://img.mini.minisns.cn/images/page/page-menu-1.jpg" style=" width: 100%; "></div>';
                }, '');
                if($form->isCreating()){
                    $form->multipleSelectTable('config2', '选择菜单') ->title('图标库')
                        ->max(100)
                        ->from(IconRender::make())
                        ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config2')
                        ->help('一个图标即一个菜单，图标仅需配置图片， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>');
                }else if($form->isEditing()){
                    $config2 = '';
                    if($modle->type == 2){
                        $config2 = $modle->config;
                    }
                    $form->multipleSelectTable('config2', '选择菜单') ->title('图标库')
                        ->max(100)
                        ->from(IconRender::make())
                        ->model(WxIcon::class, 'id', 'name', 'selectTable:WxPageController:config2')
                        ->help('一个图标即一个菜单，图标仅需配置图片， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>')
                        ->value($config2);
                }

            })->when(3, function (Form $form) use ($modle) {
                $form->html(function () {
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;max-width: 200px;"><img src="https://img.mini.minisns.cn/2023/08/10/3aabac910d72694bc235485b1600bce9.jpg" style=" width: 100%; "></div>';
                }, '');
                if($form->isCreating()){
                    $form->image('config3_banner_img', '头部背景图')->help('建议和默认图片大小。 <a href="https://img.mini.minisns.cn/2023/08/10/6ef83dfeade1ef3c30770e0cf0f5e6c1.jpg" download="app_login_bg.jpg" target="_blank" style="color: steelblue">点击下载默认图</a>')->url('files/uploads')->uniqueName()->autoUpload()->default('https://img.mini.minisns.cn/2023/08/10/6ef83dfeade1ef3c30770e0cf0f5e6c1.jpg');
                    $form->table('config3_tabs', 'tab-二维码', function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->image('code', '二维码')->help('建议和默认图片大小。 <a href="https://img.mini.minisns.cn/images/mmqrcode1677495496626%281%29.png" download="app_login_bg.jpg" target="_blank" style="color: steelblue">点击下载默认图</a>')->url('files/uploads')->uniqueName()->autoUpload()->default('https://img.mini.minisns.cn/images/mmqrcode1677495496626%281%29.png');
                    })->saveAsJson();
                }else if($form->isEditing()){
                    $config3_arr = json_decode($modle->config, true);
                    $form->image('config3_banner_img', '头部背景图')->help('建议和默认图片大小。 <a href="https://img.mini.minisns.cn/2023/08/10/6ef83dfeade1ef3c30770e0cf0f5e6c1.jpg" download="app_login_bg.jpg" target="_blank" style="color: steelblue">点击下载默认图</a>')->url('files/uploads')->uniqueName()->autoUpload()->customFormat(function ($v) use ($config3_arr){
                        return _array_key($config3_arr, 'banner', '');
                    });
                    $form->table('config3_tabs', 'tab-二维码', function (NestedForm $table) {
                        $table->text('name', 'tab名字');
                        $table->text('desc', '描述');
                        $table->image('code', '二维码')->help('建议和默认图片大小。 <a href="https://img.mini.minisns.cn/images/mmqrcode1677495496626%281%29.png" download="app_login_bg.jpg" target="_blank" style="color: steelblue">点击下载默认图</a>')->url('files/uploads')->uniqueName()->autoUpload()->default('https://img.mini.minisns.cn/images/mmqrcode1677495496626%281%29.png');
                    })->saveAsJson()->value(_array_key($config3_arr, 'tabs', ''));
                }
            });
            $form->radio('status')->options([0=>'正常',1=>'下架'])->default(0);
            $form->textarea('config')->disable(true)->help('保存后自动生成的，不用管');

//            $form->display('created_at');
//            $form->display('updated_at');
            $form->saving(function (Form $form) {
                $type = $form->input('type');
                if($type == 1 || $type == 0){
                    $configDate = $form->input('config'.$type);
                    if(is_array($configDate)){

                        if(_empty_($configDate)){
                            $form->config = '';
                        }else{
                            $v_ = [];
                            foreach ($configDate as $new_){
                                if(_array_key($new_, '_remove_', null) == 1){
                                    continue;
                                }
                                if(isset($new_['_remove_'])){
                                    unset($new_['_remove_']);
                                }
                                $v_[] = $new_;
                            }
                            if(0){
                                $form->config = $v_;
                            }else{
                                $form->config = json_encode($v_);
                            }
                        }

                    }
                }else if($type == 2){
                    $configDate = $form->input('config'.$type);
                    $form->config = $configDate;
                }else if($type == 3){
                    $config3_data = [
                        'banner' => $form->input('config3_banner_img'),
                        'tabs' => ''
                    ];
                    $config3_tabs = $form->input('config3_tabs');
                    if(is_array($config3_tabs)){
                        if(_empty_($config3_tabs)){

                        }else{
                            $v_ = [];
                            foreach ($config3_tabs as $new_){
                                if(_array_key($new_, '_remove_', null) == 1){
                                    continue;
                                }
                                if(isset($new_['_remove_'])){
                                    unset($new_['_remove_']);
                                }
                                $v_[] = $new_;
                            }
                            $config3_data['tabs'] = json_encode($v_);
                        }
                    }
                    if(_empty_($config3_data['tabs'])){
                        $config3_data['tabs'] = $config3_data;
                    }
                    $form->config = json_encode($config3_data);
                }

                // 删除
                $form->deleteInput(['config0', 'config1', 'config2', 'config3_banner_img', 'config3_tabs']);
                $form->ignore(['config0', 'config1', 'config2', 'config3_banner_img', 'config3_tabs']);
            });

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
            });

        });
    }

}
